using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace SPDWorkflowStringActions
{
    class SPDWorkflowStringActionsFeatureReceiver : SPFeatureReceiver
    {
        const string webConfigModificationName = "authorizedType[@Assembly='SPDWorkflowStringActions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=3825586d873cffa1'][@Namespace='SPDGenericActions'][@TypeName='*'][@Authorized='True']";
        const string webConfigModificationOwner = "YarraCity";

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            //throw new Exception("The method or operation is not implemented.");
            SPWebApplication thisWebApp = (SPWebApplication)properties.Feature.Parent;
            
            SPWebConfigModification thisModification = new SPWebConfigModification();
            thisModification.Path = "configuration/System.Workflow.ComponentModel.WorkflowCompiler/authorizedTypes";
            thisModification.Name = webConfigModificationName;
            thisModification.Sequence = 0;
            thisModification.Owner = webConfigModificationOwner;
            thisModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
            thisModification.Value = "<authorizedType Assembly=\"SPDWorkflowStringActions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=3825586d873cffa1\" Namespace=\"SPDWorkflowStringActions\" TypeName=\"*\" Authorized=\"True\" />";

            thisWebApp.WebConfigModifications.Add(thisModification);
            thisWebApp.Update();
            try
            {
                thisWebApp.WebService.ApplyWebConfigModifications();
            }
            catch (SPException ex)
            {
                if (ex.Message.StartsWith("Failed to apply a web.config"))
                {

                    int previousNumberOfMods = thisWebApp.WebService.WebConfigModifications.Count + thisWebApp.WebConfigModifications.Count;
                    thisWebApp.WebConfigModifications.Clear();
                    thisWebApp.Update();
                    thisWebApp.WebService.WebConfigModifications.Clear();
                    thisWebApp.WebService.Update();
                    //thisWebApp.WebService.ApplyWebConfigModifications();

                    throw new SPException("Failure to perform an update to web.config due to erroneous pending changes.  All pending updates have been cleared (found " + previousNumberOfMods.ToString() + " of them). Try activating this feature again.");
                }
                else
                {

                    System.Diagnostics.EventLog.WriteEntry("SPDWorkflowStringActionsFeatureReceiver", "SPException occurred");
                    throw new SPException(ex.Message);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("SPDWorkflowStringActionsFeatureReceiver", "Exception occurred");
                throw new Exception("", ex);
            }
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {

            SPWebApplication thisWebApp = (SPWebApplication)properties.Feature.Parent;
            
            //throw new Exception("The method or operation is not implemented.");
            SPWebConfigModification configModFound = null;
            Collection<SPWebConfigModification> modsCollection = thisWebApp.WebConfigModifications;

            // Find the most recent modification of a specified owner
            int modsCount1 = modsCollection.Count;
            int modIndexToRemove = 0;
            bool foundMod = false;

            for (int i = modsCount1 - 1; i > -1; i--)
            {
                if (modsCollection[i].Owner == webConfigModificationOwner && modsCollection[i].Name == webConfigModificationName)
                {
                    thisWebApp.WebConfigModifications.RemoveAt(i);
                    foundMod = true;
                }
            }

            if (foundMod)
            {
                thisWebApp.Update();
                thisWebApp.WebService.ApplyWebConfigModifications();
                thisWebApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
            }

            // Remove it and save the change to the configuration database  
            /*if (configModFound != null)
            {
                System.Diagnostics.EventLog.WriteEntry("SPDWorkflowStringActionsFeatureReceiver", "Found and removing config modification: " + modsCollection[modIndexToRemove].Name);
                //modsCollection.Remove(configModFound);
                

                // Reapply all the configuration modifications
                //thisWebApp.WebService.ApplyWebConfigModifications();
            }*/
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
            //throw new Exception("The method or operation is not implemented.");
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            //throw new Exception("The method or operation is not implemented.");
        }
    }
}
